from django.db.models import SubfieldBase
from django.db.models.fields import TextField
from django.utils.encoding import smart_str
import forms 


class AnswersField(TextField):
    __metaclass__ = SubfieldBase

    def formfield(self, **kwargs):
        defaults = {
            'form_class': forms.AnswersField,
        }
        defaults.update(kwargs)
        return super(AnswersField, self).formfield(**defaults)

    def to_python(self, value):
        if value is None:
            return []
        if isinstance(value, (list, tuple)):
            return value
        
        # Probably a string - attempt to split it
        try:
            return value.splitlines()
        except: # TODO: Better error handling?
            return []

    def get_db_prep_value(self, value):
        value = self.to_python(value)
        if len(value) == 0: # No answers yet
            return None
        return '\n'.join(value)
  
    def get_db_prep_lookup(self, lookup_type, value): # TODO: Implement
        raise TypeError('Lookup type %r not supported.' % lookup_type)
  
    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)
